﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using AppDomainToolkit;
using ZilLion.Core.Log;
using ZilLion.Core.TaskManager.Client.Core;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.TaskManager.Entity.Entity;
using ZilLion.TaskManager.Repository;


namespace ZilLion.Core.TaskManager.Client.Command
{
    /// <summary>
    ///     开启任务命令
    /// </summary>
    public class StartTaskCommand : BaseCommand
    {
        private readonly TaskConfigRespository _taskConfigRespository = new TaskConfigRespository();
        private readonly TaskModuleConfigRespository _taskModuleRespository = new TaskModuleConfigRespository();

        public override void Execute()
        {
          

            TaskConfig taskConfig = null;
            var response = _taskConfigRespository.GetTaskConfigById(CommandInfo.Taskid);

            if ((response != null) && (response.TaskConfigList != null))
                taskConfig = response.TaskConfigList.FirstOrDefault();
            if (taskConfig == null)
            {
                ZilLionLogManager.GetLogger().Warn($"{CommandInfo.Taskid}找不到对应CONFIG");
            }

            else
            {
                if (!PreparePackage(taskConfig))
                {
                    ZilLionLogManager.GetLogger().Warn($"{CommandInfo.Taskid}包文件准备失败");
                }
             
                else
                {
        
                    TaskExcuteProvider.GetInstance().StartTask(taskConfig);
                }
              
            }
        }

        private bool PreparePackage(TaskConfig config)
        {
            try
            {
                TaskModuleConfigEntity taskModuleConfigEntity = null;

                #region 下载

                var response = _taskModuleRespository.GetTaskModuleConfigById(config.TaskmoduleId);

                if ((response != null) && (response.TaskModuleList != null) &&
                    (response.TaskModuleList.FirstOrDefault() != null))
                    taskModuleConfigEntity = response.TaskModuleList.FirstOrDefault();
                if (taskModuleConfigEntity == null) return false;


                var packagepath = Path.Combine(AppUrlHelper.AppDataLocalPath, "TaskPackage", "PackageCache");
                if (!Directory.Exists(packagepath))
                    Directory.CreateDirectory(packagepath);
                var filepath = Path.Combine(packagepath, config.TaskmoduleId + ".taskpackage");
                if (!CheckPackageValid(filepath, taskModuleConfigEntity.Taskmodulepackagecrc)) //如果文件无效重新下载
                {
                    ZilLionLogManager.GetLogger().Trace($"{config.Taskid}包文件有误，重新下载");
                    if (File.Exists(filepath))
                        File.Delete(filepath); //删除

                    if (_taskConfigRespository.DownLoadPackage(taskModuleConfigEntity.TaskmoduleId, filepath))
                    {
                        var packagedllpath = Path.Combine(FileHelper.GetRootPath(), $"Package_{config.TaskModule}");
                        CompressHelper.UnZip(filepath, packagedllpath);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                ZilLionLogManager.GetLogger().Error(ex);
                return false;
            }
            return true;
        }


        /// <summary>
        ///     判断包文件是否有效
        /// </summary>
        /// <returns></returns>
        private bool CheckPackageValid(string filepath, string taskmodulepackagecrc = null)
        {
            if (!File.Exists(filepath))
                return false;

            if (taskmodulepackagecrc.IsNotNullOrEmpty())
                using (var stream = File.OpenRead(filepath))
                {
                    if (stream.ToMD5Hash() != taskmodulepackagecrc) //如果crc码和本地不一致，需要
                        return false;
                }
            return true;
        }
    }
}